import axios from 'axios'
import aes from './aes.js'
import rsa from './rsa.js'
import { Message } from 'element-ui'
import { apiUrl } from './branch'

function GetQueryString(str) {
  var str = JSON.parse(str)
  return str.key
}

function dt(data) {
  for (let i in data) {
    if( data[i] === null || data[i] === undefined)
    delete data[i]
  }
  return data
}

function commonFun(config) {
  console.log(config.data, config.url)
  var data = JSON.stringify(dt(config.data))
  var string = aes.randomString(16)
  let key = rsa.RSAencrypt(string)
  let _key = rsa.RSAdencrypt(key)
  var params = {
    key: rsa.RSAencrypt(string),
    data: aes.Encrypt(data || null, string),
    defaultKey: string
  }
  return params
}

export const officialURL = process.env.NODE_ENV == 'development' ? '192.168.2.34:6677' : apiUrl
// export const officialURL =  `192.168.199.245:9999`


// 异常拦截处理器
const errorHandler = (error) => {
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    const token = localstorage.getItem(ACCESS_TOKEN)
    if (error.response.status === 403) {
      // notification.error({
      //   message: 'Forbidden',
      //   description: data.message
      // })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      // notification.error({
      //   message: 'Unauthorized',
      //   description: 'Authorization verification failed'
      // })
      // if (token) {
      //   store.dispatch('Logout').then(() => {
      //     setTimeout(() => {
      //       window.location.reload()
      //     }, 1500)
      //   })
      // }
    }
  }
  return Promise.reject(error)
}
// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: `//${officialURL}`,
  // baseURL: '/dev-api',
  withCredentials: true // send cookies when cross-domain requests
  // timeout: 5000 // request timeout
})


service.interceptors.request.use(config => {
  
  
  config.headers['Content-Type'] = 'application/json';
  const commonData = commonFun(config)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  // 加入'application/json'
  delete commonData.defaultKey

  config.data = commonData
  // config.data = commonData.data
  return config
}, errorHandler)

// service.interceptors.request.use(
//   config => {
//     if(config.data){
//       let data = renderData(config.data || {})
//       config.data = data;
//     }else{
//       config.data = new FormData()
//     }
    
//     config.headers['Content-Type'] = 'application/json'
//     return config
//   },
//   error => {
//     // do something with request error
//     console.log(error) // for debugm
//     return Promise.reject(error)
//   }
// )

// response interceptor
service.interceptors.response.use((response) => {
  const res = response.data
  if (response.status == 200 && (response.data.code == 1)) {
    console.log(response.data)
    //  解密
    const str = rsa.RSAdencrypt(GetQueryString(response.config.data))
    if (response.data.data) {
      response.data.data = response.data.data.replace(/\s/g,'')
      try {
        response.data.data = JSON.parse(aes.Decrypt(response.data.data, str))
      } catch (e) {
        // TODO handle the exception
        response.data.data = aes.Decrypt(response.data.data, str)
      }
    }
    console.log(response.data,response.config.url)
    return response.data
  } else if(response.status == 200 && (response.data.code == 1030)){
    return response.data
  } else {
    Message.error({
      content: res.msg,
    })
    return Promise.reject(new Error(`${res.code}:${res.msg}`))
  }
}, errorHandler)

export default service
